package br.com.serialmanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import br.com.serialmanager.model.bean.Mascara;
import br.com.serialmanager.model.bean.Software;
import br.com.serialmanager.model.dao.MascaraDao;
import br.com.serialmanager.model.dao.SoftwareDao;
import br.com.serialmanager.webservice.HttpSoapRequest;

public class ListaSoftwareActivity extends Activity implements OnClickListener, OnItemClickListener, Runnable {
	
	private static final String EXTRA_SOFTWARE_ID = "EXTRA_SOFTWARE_ID";
	
	private ProgressDialog progressDialog;
	private AlertDialog dialogVisualizacao;
	private AlertDialog dialogOpcoes;
	private AlertDialog dialogConfirmacao;
	private SoftwareDao softwareDao;
	private SimpleAdapter adapter;
	private ListView listaSoftwares;
	private Button btnAtualizarTodos;
	private int[] para = {R.id.txtNomeSoftware, R.id.txtNumeroDeSerie};
	private String[] de = {"nome_software", "numero_de_serie"};
	private List<Map<String, Object>> softwares;
	private int itemSelecionado;
	private Handler handler;
	private MascaraDao mascaraDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.listar_softwares);
		
		this.dialogConfirmacao = this.criarDialogConfirmacao();
		this.dialogOpcoes = this.criarDialogOpcoes();
		
		this.mascaraDao = new MascaraDao(this);
		this.softwareDao = new SoftwareDao(this);
		this.softwares = new ArrayList<Map<String, Object>>();
		this.btnAtualizarTodos = (Button) this.findViewById(R.id.atualizarTodos);
		this.listaSoftwares = (ListView) this.findViewById(R.id.listagemSoftwares);
		
		this.listaSoftwares.setOnItemClickListener(this);
		
		this.handler = new Handler() {
			public void handleMessage(Message msg) {
				updateUI(msg);
			}
		};
	}
	
	private AlertDialog criarDialogVisualizacao() {
		// TODO Auto-generated method stub
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		LayoutInflater inflater = LayoutInflater.from(this);
		View dialogView = inflater.inflate(R.layout.dialog_view_software, null);
		
		TextView txtNomeSoftware = (TextView) dialogView.findViewById(R.id.dialogTxtNomeSoftware);
		txtNomeSoftware.setText(this.softwares.get(this.itemSelecionado).get("nome_software").toString());
		
		TextView txtValidadeSoftware = (TextView) dialogView.findViewById(R.id.dialogTxtValidade);
		Date validade = (Date) this.softwares.get(this.itemSelecionado).get("data_validade");
		if (validade != null)
			txtValidadeSoftware.setText(formatter.format(this.softwares.get(this.itemSelecionado).get("data_validade")));
		else
			txtValidadeSoftware.setText(getString(R.string.indefinido));
		
		TextView txtNumeroDeSerie = (TextView) dialogView.findViewById(R.id.dialogTxtNumeroDeSerie);
		txtNumeroDeSerie.setText(this.softwares.get(this.itemSelecionado).get("numero_de_serie").toString());
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.visualizacao_do_software);
		builder.setView(dialogView);
		builder.setNeutralButton(R.string.fechar, this);
		return builder.create();
	}

	private AlertDialog criarDialogOpcoes() {
		// TODO Auto-generated method stub
		final CharSequence[] items = {
				getString(R.string.visualizar),
				getString(R.string.editar),
				getString(R.string.remover),
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.opcoes));
		builder.setItems(items, this);
		return builder.create();
	}

	private AlertDialog criarDialogConfirmacao() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.mensagem_confirmacao_excluir);
		builder.setPositiveButton(R.string.sim, this);
		builder.setNegativeButton(R.string.nao, this);
		return builder.create();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.adapter = new SimpleAdapter(this, this.getListaSoftwares(), R.layout.layout_lista_softwares, this.de, this.para);
		this.listaSoftwares.setAdapter(this.adapter);
	}
	
	public void atualizarTodos(View view) {
		this.progressDialog = ProgressDialog.show(this, null, "Atualizando registros...", true);
		new Thread(ListaSoftwareActivity.this).start();
	}
	
	private List<Map<String, Object>> getListaSoftwares() {
		this.softwares = this.softwareDao.listarSoftwares(); 
		return this.softwares;
	}

	private void apagarSoftware() {
		// TODO Auto-generated method stub
		if (this.softwareDao.apagarSoftware(this.softwares.get(this.itemSelecionado).get("soft_id").toString())) {
			Toast.makeText(this, R.string.registro_apagado, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, R.string.erro_apagar, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		switch (which) {
			case 0:
				this.dialogVisualizacao.show();
				break;
			case 1:
				Intent intent = new Intent(this, NovoSoftwareActivity.class);
				intent.putExtra(EXTRA_SOFTWARE_ID, this.softwares.get(this.itemSelecionado).get("soft_id").toString());
				this.startActivity(intent);
				break;
			case 2:
				this.dialogConfirmacao.show();
				break;
			case DialogInterface.BUTTON_POSITIVE:
				this.apagarSoftware();
				this.softwares.remove(this.itemSelecionado);
				this.listaSoftwares.invalidateViews();
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				this.dialogConfirmacao.dismiss();
				break;
			case DialogInterface.BUTTON_NEUTRAL:
				this.dialogVisualizacao.dismiss();
				break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		this.itemSelecionado = position;
		this.dialogVisualizacao = this.criarDialogVisualizacao();
		this.dialogOpcoes.show();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		HttpSoapRequest soapRequest = new HttpSoapRequest("server.smanager", "http://www.rodrigootacilio.com.br/ws/server.php", "getSoftwares");
		try {
			soapRequest.makeRequest();
			Object response = soapRequest.getResponse();
			this.atualizaDados(response);
			this.progressDialog.dismiss();
		} catch (Exception e) {
			Log.e("ERROR", e.getMessage());
			e.printStackTrace();
			this.progressDialog.dismiss();
		}
		Message message = new Message();
		message.what = 1;
		handler.sendMessage(message);
	}
	
	private void atualizaDados(Object resp) {
		Log.d("RESP", resp.toString());
		String[] response = resp.toString().split(",");
		Calendar calendar = Calendar.getInstance();
		for (String str : response) {
			String[] atual = str.replace("[", "").replace("]", "").split(":");
			Software software = this.softwareDao.carregarPorNumeroDeSerie(atual[3]);
			if (software == null) {
				Date validadeSoftware = null;
				if (atual[2].length() > 0) {
					String[] dataValidade = atual[2].split("-");
					calendar.set(Integer.parseInt(dataValidade[0]), Integer.parseInt(dataValidade[1]), Integer.parseInt(dataValidade[2]));
					validadeSoftware = calendar.getTime();
				}
				Mascara masc = this.getMascara(atual[3]);
				software = new Software(atual[1], validadeSoftware, atual[3], masc.getId());
				this.softwareDao.salvarSoftware(software);
			}
		}
	}
	
	private void updateUI(Message message) {
		if (message.what == 1) {
			this.adapter = new SimpleAdapter(this, this.getListaSoftwares(), R.layout.layout_lista_softwares, this.de, this.para);
			this.listaSoftwares.setAdapter(this.adapter);
		}
	}
	
	private Mascara getMascara(String numeroDeSerie) {
		StringBuilder format = new StringBuilder();
		for (int i = 0; i < numeroDeSerie.length(); i++) {
			boolean condicao = (numeroDeSerie.charAt(i) != '-' && numeroDeSerie.charAt(i) != '_' &&
					numeroDeSerie.charAt(i) != '.');
			if (condicao) {
				format.append("#");
			} else {
				format.append(numeroDeSerie.charAt(i));
			}
		}
		Mascara mascara = this.mascaraDao.carregarPorFormato(format.toString());
		if (mascara == null) {
			mascara = new Mascara(format.toString());
			this.mascaraDao.salvarMascara(mascara);
		}
		return mascara;
	}
}
